<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 自定义组件，标题 -->
      <PageTitle :show-before="true">
        <template v-slot:before>
          <h2>招聘会管理</h2>
        </template>
      </PageTitle>
      <el-row type="flex" :gutter="10" style="margin-top: 10px">
        <el-col :span="16">
          <el-select
            v-model="selJobFair.date"
            placeholder="不限添加时间"
            clearable
            @change="handleAddtimeChange"
          >
            <el-option
              v-for="item in addTime"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>

        <el-col :span="8">
          <el-row type="flex">
            <el-col :span="8">
              <el-select
                v-model.number="selJobFair.keyType"
                placeholder="标题"
                clearable
                @change="handleTitleChange"
              >
                <el-option :value="1" label="标题"></el-option>
                <el-option :value="2" label="招聘会ID"></el-option>
              </el-select>
            </el-col>
            <el-col :span="16">
              <el-row :gutter="10" type="flex">
                <el-input
                  v-model="selJobFair.keyword"
                  placeholder="请输入搜索内容"
                  @keyup.enter.native="searchClick"
                ></el-input>
                <el-button type="primary" @click="searchClick">
                  <i class="el-icon-search"></i>
                </el-button>
              </el-row>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <!-- 数据表 -->
      <el-table
        ref="jobFairTable"
        v-loading="downloadLoading"
        ooltip-effect="dark"
        :data="selJobFairLists"
        style="margin-top: 20px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" fixed />
        <el-table-column
          label="标题"
          align="center"
          prop="title"
          fixed
          width="280"
        >
          <template slot-scope="scope">
            <!-- <el-link type="primary" :href="scope.row.jobfairLink">{{
              scope.row.title
            }}</el-link> -->
            <el-tooltip
              class="item"
              effect="dark"
              :content="scope.row.title"
              placement="top-start"
            >
              <el-button type="text">{{ scope.row.title }}</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          label="举办时间"
          align="center"
          width="320"
          prop="holdStartTime"
          fixed
        >
          <template slot-scope="scope">
            <!-- <el-tooltip
              placement="top"
              :content="`${scope.row.holdStartTime | dateFormat} 至 ${
                scope.row.holdEndTime | dateFormat
              }`"
            > -->
            <span
              >{{ scope.row.holdStartTime | dateFormat }} 至
              {{ scope.row.holdEndTime | dateFormat }}</span
            >
            <!-- </el-tooltip> -->
          </template>
        </el-table-column>
        <el-table-column label="显示状态" align="center" prop="display">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.display"
              @change="handleSwitch(scope.row.id)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="刷新时间"
          align="center"
          prop="addtime"
          width="180"
        >
          <template slot-scope="scope">
            <i class="el-icon-time"></i> {{ scope.row.addtime | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="prop" label="参会企业/个人" width="120">
          <template slot-scope="scope">
            {{ scope.row.totalCompany }}/{{ scope.row.totalPersonal }}
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          prop="prop"
          label="操作"
          width="400"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="small"
              @click="participation(scope.row.id)"
              >参会企业</el-button
            >
            <!-- <el-button
              type="primary"
              size="small"
              @click="personEnterprise(scope.row.id)"
              >参会个人</el-button
            > -->
            <el-button
              type="primary"
              size="small"
              @click="editJobFair(scope.row.id)"
              >编辑</el-button
            >
            <!-- <el-button
              type="primary"
              size="small"
              @click="detaliClick(scope.row.id)"
              >详情</el-button
            > -->
            <el-button type="danger" size="small" @click="delBtn(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-row :gutter="10" style="margin-top: 20px">
        <el-col :span="8">
          <el-button type="primary" size="small" @click="addJobFair"
            >添加招聘会</el-button
          >
          <!-- <el-button type="danger" size="small" @click="deleteSelected"
            >删除所选</el-button
          > -->
          <!-- <el-button type="primary" size="small" @click="exportExcel"
            >导出Excel</el-button
          > -->
        </el-col>
        <el-col :span="16">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="selJobFair.page"
            :page-sizes="[10, 20, 50]"
            :page-size="selJobFair.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            style="text-align: right"
          >
          </el-pagination>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import {
  selJobFairListApi,
  delJobFairByIdsApi,
  updateJobFairDisplayApi,
  selJobFairByIdApi,
  exportExcelApi,
} from "@/api/application";
export default {
  data() {
    return {
      value1: true,
      total: "",
      downloadLoading: true,
      model1: [{ id: 1, name: "标题" }],
      // 招聘会请求参数
      selJobFair: {
        page: 1,
        pageSize: 10,
        date: "",
        keyType: 1,
        keyword: "",
      },
      id: "",
      selJobFairLists: [],
      ids: [],
      reserveStatus: [
        { id: 1, name: "不限预定状态" },
        { id: 2, name: "未开始预定" },
        { id: 3, name: "永许预定" },
        { id: 4, name: "停止预定" },
      ],
      addTime: [
        { value: "", name: "不限添加时间" },
        { value: 3, name: "三天内" },
        { value: 7, name: "一周内" },
        { value: 30, name: "一月内" },
        { value: 180, name: "半年内" },
        { value: 360, name: "一年内" },
      ],
    };
  },
  created() {
    this.selJobFairList();
  },
  methods: {
    // 导出Excel
    async exportExcel() {
      console.log(this.id);
      if (!this.id) {
        this.$message.warning("请选择招聘会");
        return;
      }
      let loading = null;
      try {
        await this.$confirm(
          "此操作将导出招聘会下所有企业和职位, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );

        // 显示loading
        loading = this.$loading({
          lock: true,
          text: "正在导出数据,请稍候...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });

        const res = await exportExcelApi(this.id);

        if (res.code === 1 && res.data) {
          // 创建a标签下载
          const link = document.createElement("a");
          link.href = res.data;
          link.download = "招聘会下企业和岗位信息导出.xlsx";
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          this.$message.success("导出成功");
          this.$refs.jobFairTable.clearSelection();
          this.id = "";
        } else {
          this.$message.error(res.msg);
          this.$refs.jobFairTable.clearSelection();
        }
      } catch (error) {
        // console.error("导出错误:", error);
        // this.$message.error("导出失败");
      } finally {
        // 关闭loading
        if (loading) {
          loading.close();
        }
      }
    },
    // 选择招聘会的时候
    handleSelectionChange(selection) {
      console.log(selection);
      this.ids = selection.map((item) => item.id);
      console.log(this.ids);
      if (selection.length > 1) {
        // 清除之前的选择
        this.$refs.jobFairTable.clearSelection();
        // 只保留最新选择的行
        const lastSelected = selection[selection.length - 1];
        this.$refs.jobFairTable.toggleRowSelection(lastSelected, true);
        // 更新 id 和选中项
        console.log(lastSelected);

        this.id = lastSelected.id;
      } else {
        // 只有一个选择时直接更新
        this.id = selection[0]?.id || "";
      }
    },
    searchClick() {
      this.selJobFairList();
    },
    // 选择类型的时候
    handleTitleChange(value) {
      console.log(value);
      this.selJobFair.page = 1;
      this.selJobFairList();
    },
    // 选择添加时间的时候
    handleAddtimeChange(value) {
      console.log(value);
      this.selJobFair.page = 1;
      this.selJobFairList();
    },
    // 列表渲染
    async selJobFairList() {
      try {
        const res = await selJobFairListApi(this.selJobFair);
        this.selJobFairLists = res.records.map((item) => ({
          ...item,
          display: item.display === 1 ? true : false,
        }));
        console.log(this.selJobFairLists);
        this.total = res.total;
      } catch {
      } finally {
        this.downloadLoading = false;
      }
    },
    // 设置显示状态
    async handleSwitch(id) {
      // console.log(id);
      try {
        const res = await updateJobFairDisplayApi(id);
        console.log(res);
        if (res.code === 1) {
          this.$message.success("设置成功");
          this.selJobFairList();
        } else {
          this.$message.error("设置失败");
        }
      } catch {
        this.$message.error("设置失败");
      }
    },
    // 添加招聘会
    addJobFair() {
      this.$router.push({
        name: "addJobFair",
      });
    },
    // 编辑招聘会
    async editJobFair(id) {
      // console.log(row);
      console.log(id);
      const res = await selJobFairByIdApi(id);
      console.log(res);
      if (res.code === 1) {
        // 存储详情数据到localStorage
        localStorage.setItem("editJobFair", JSON.stringify(res.data));
        this.$router.push({
          name: "editJobFair",
        });
      } else {
      }
    },
    // 参会企业
    participation(id) {
      this.$router.push({
        name: "participation",
        query: {
          id: id,
        },
      });
      localStorage.setItem("selCompanyListQuery", JSON.stringify(id));
      // console.log(id);
      // this.$bus.$emit("CompanyList", id);
    },
    // 参会个人
    personEnterprise(id) {
      this.$router.push({
        name: "personEnterprise",
        params: {
          id: id,
        },
      });
      localStorage.setItem("selCompanyGrListQuery", JSON.stringify(id));
      // localStorage.setItem('selCompanyGrListQuery', JSON.stringify(id))
    },
    // 删除招聘会
    delBtn(id) {
      this.$confirm("此操作将永久删除该招聘会, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            this.ids.push(id);
            const res = await delJobFairByIdsApi(this.ids);
            console.log(res);
            if (res.code === 1) {
              this.$message.success("删除成功");
              this.ids = [];
              this.selJobFairList();
            } else {
              this.$message.error("删除失败");
            }
          } catch {
            this.$message.error("删除失败");
          }
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "已取消删除",
          // });
        });
    },
    // 删除所选
    deleteSelected() {
      try {
        if (this.ids.length === 0) {
          this.$message.error("请选择要删除的数据");
          return;
        }
        this.$confirm("此操作将永久删除该招聘会, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            const res = await delJobFairByIdsApi(this.ids);
            console.log(res);
            if (res.code === 1) {
              this.$message.success("删除成功");
              this.ids = [];
              this.selJobFairList();
            } else {
              this.$message.error("删除失败");
            }
          })
          .catch(() => {
            // this.$message({
            //   type: "info",
            //   message: "已取消删除",
            // });
          });
      } catch {
        this.$message.error("删除失败");
      }
    },
    // 详情
    async detaliClick(id) {
      console.log(id);
      const res = await selJobFairByIdApi(id);
      console.log(res);
    },
    // 每页显示的条数发生变化
    handleSizeChange(pageSize) {
      this.selJobFair.pageSize = pageSize;
      // 重新获取列表数据
      this.selJobFairList();
    },
    // 点击了分页组件的页面的时候
    handleCurrentChange(page) {
      this.selJobFair.page = page;
      // 重新获取列表数据
      this.selJobFairList();
    },
    // 展位设置
    boothSetup() {
      this.$router.push({
        name: "boothSetup",
      });
    },
    // 处理地区选择变化
    handleDistrictChange(value) {
      // 直接使用完整的选择数组
      console.log(value);
      // 重新获取列表数据
      this.selJobFairList();
    },
  },
};
</script>

<style scoped></style>
